//
//  ChatMessageTableView.swift
//  puretennis
//
//  Created by Derek Zheng on 1/7/15.
//  Copyright (c) 2015 IYE Technologies. All rights reserved.
//

import Foundation

class ChatMessageTableView: UITableView, UITableViewDelegate, UITableViewDataSource{
    
    //identifier = the user guid of the user details view
    var identifier: String?
    
    var currentUserGuid = Utils.getValue("guid") as String
    
    var messageList:[NSDictionary] = []
    
    var messageCells:[UITableViewCell] = []
    
    var chatLocalDataIdentifier: String?
    
    init(identifier: String) {
        super.init()
        self.identifier = identifier
        self.delegate = self
        self.dataSource = self
        self.separatorStyle = UITableViewCellSeparatorStyle.None
        self.chatLocalDataIdentifier = "chat_\(self.currentUserGuid)@\(identifier)"
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame:frame, style: style)
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
        
    func retrieveDataFromLocalStorage(){
        
        var list: AnyObject? = Utils.getValue(self.chatLocalDataIdentifier!)
        
        if(list != nil){
            self.messageList = list as [NSDictionary]
        }
        
        var url = "/api/v1/chat/read?identifier=" + self.identifier!
        
        var response = HttpUtils.sendSynchronousRequest(url, method: RequestMethod.GET, requestBody: nil) as [String]
        
        var messages = response as [String]
        
        if(messages.count > 0){
            for message in messages{
                self.addMessage(Utils.jsonToNSDictionary(message)!)
            }
        }
        self.reloadData()
    }
    
    
    override func reloadData() {
        self.messageCells.removeAll()
        var index = 0
        for message in self.messageList{
            let cell = self.initiateTableCell(self, message: message, index: index)
            self.messageCells.append(cell)
            index++
        }
        super.reloadData()
    }
        
    func initiateTableCell(tableView: UITableView, message: NSDictionary, index: Int) -> UITableViewCell{

        var cell = UITableViewCell()
        
        let height = cell.frame.height
        cell.backgroundColor = UIColor.clearColor()
        var senderGuid = (message.objectForKey("sender") as String)
        
        var avatarImage = ImageUtils.retrieveUserImage(senderGuid)
        var avatar = UIImageView(image: avatarImage)
        
        let size = CGSize(width: height * 0.85, height: height * 0.85);
        avatar.frame.size = size;
        
        let originX:CGFloat = 5;
        let originY:CGFloat = (height - size.height - 4) / 2;
        avatar.frame.origin = CGPoint(x: originX, y: originY);
        
        avatar.layer.masksToBounds = true;
        avatar.layer.cornerRadius = avatar.frame.height * 0.5;
        
        cell.addSubview(avatar);
        
        
        var messageLabel = UITextView()
        messageLabel.editable = false
        messageLabel.scrollEnabled = false
        messageLabel.layer.cornerRadius = 10
        messageLabel.backgroundColor = ViewUtils.colorWithHexString("E0EFFC")
        messageLabel.frame.size.width = tableView.frame.width - 12 - avatar.frame.width
        messageLabel.textAlignment = NSTextAlignment.Left;
        messageLabel.textColor = UIColor.blackColor();
        messageLabel.font = Utils.systemFont(16)
        var messageText = (message.objectForKey("message") as String)
        messageLabel.text = messageText
        
        let messageLabelOriginX = avatar.frame.origin.x + avatar.frame.width + 5;
        let messageLabelOriginY = (height - messageLabel.frame.height - 4) / 2;
        messageLabel.frame.origin = CGPoint(x: messageLabelOriginX, y: messageLabelOriginY);
        messageLabel.sizeToFit()
        
        
        if(senderGuid != self.currentUserGuid){
            messageLabel.backgroundColor = ViewUtils.colorWithHexString("E7E9EA")
            var messageLabelPos = messageLabel.frame.origin
            avatar.frame.origin.x = tableView.frame.width - 5 - avatar.frame.width
            messageLabel.frame.origin.x = avatar.frame.origin.x - messageLabel.frame.width - 5
        }
        
        
        
        cell.addSubview(messageLabel);
        
        let cellHeight = messageLabelOriginY * 2 + messageLabel.frame.height  - cell.frame.origin.y
        cell.frame.size.height = cellHeight
        
        
        var timeLabel = UILabel()
        var time: AnyObject? = message.objectForKey("time")
        if(time != nil){
            timeLabel.text = time as? String
            timeLabel.textColor = UIColor.grayColor()
            timeLabel.font = Utils.systemFont(12)
            timeLabel.frame.size.width = tableView.frame.width - 12 - avatar.frame.width
            timeLabel.sizeToFit()
            var posX = avatar.frame.origin.x
            
            if(senderGuid != self.currentUserGuid){
                posX -= timeLabel.frame.width + 5
            }else{
                posX += avatar.frame.width + 5
            }
            
            timeLabel.frame.origin = CGPoint(x: posX, y: avatar.frame.origin.y)
            
            cell.addSubview(timeLabel)
        }
        
        return cell
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
        var messageCell = self.messageCells.reverse()[indexPath.row]
        return messageCell.frame.height
    }

    func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool{
        return false
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return messageList.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        return self.messageCells.reverse()[indexPath.row]
    }
    
    func addMessage(message: NSDictionary){
        self.messageList.append(message)
        
        if(messageList.count > 100){
            messageList.removeAtIndex(0)
        }
        
        self.reloadData()
        
        if(identifier != nil){
            Utils.saveData(messageList, key: self.chatLocalDataIdentifier!)
        }
    }
    
}
